const app = getApp()
const db = wx.cloud.database()
const _ = db.command

const to = app.require("lib/awaitTo")
module.exports = {
    data: {
        favorLoading: false
    },
    async favor() {
        // 点赞操作
        if (this.data.favorLoading) return
        const {
            _id,
            isFavor,
            favorNum
        } = this.data.post
        this.setData({
            favorLoading: true
        })
        const [err, res] = await to(db.collection("post")
            .doc(_id)
            .update({
                data: {
                    favor: isFavor ? _.pull(this.data.user._id) : _.push(this.data.user._id),
                    favorNum: _.inc(isFavor ? -1 : 1)
                }
            }), "favor")
        this.setData({
            favorLoading: false
        })
        if (err) {
            return
        } !isFavor && this.addMessage({ type: "favor" })
        this.setData({
            "post.isFavor": !isFavor,
            "post.favorNum": isFavor ? favorNum - 1 : favorNum + 1
        })
        wx.showToast({
            title: isFavor ? '取消点赞' : '点赞成功',
            icon: "none"
        })
    },
}